package com.lw.leetcode.tree.b;

import java.util.Arrays;

/**
 * Created with IntelliJ IDEA.
 * 1361. 验证二叉树
 *
 * @author liw
 * @version 1.0
 * @date 2022/7/2 12:29
 */
public class ValidateBinaryTreeNodes {

    private int[] leftChild;
    private int[] rightChild;

    public boolean validateBinaryTreeNodes(int n, int[] leftChild, int[] rightChild) {
        int[] arr = new int[n];
        for (int i : leftChild) {
            if (i == -1) {
                continue;
            }
            arr[i] = 1;
        }
        for (int i : rightChild) {
            if (i == -1) {
                continue;
            }
            arr[i] = 1;
        }
        int root = -1;
        for (int i = 0; i < n; i++) {
            if (arr[i] == 0) {
                if (root != -1) {
                    return false;
                }
                root = i;
            }
        }
        if (root == -1) {
            return false;
        }
        this.leftChild = leftChild;
        this.rightChild = rightChild;
        Arrays.fill(arr, 0);
        boolean f =  find(arr, root);
        if (!f) {
            return false;
        }
        for (int i : arr) {
            if (i == 0) {
                return false;
            }
        }
        return true;
    }

    private boolean find(int[] arr, int node) {
        if (node == -1) {
            return true;
        }
        if (arr[node] == 1) {
            return false;
        }
        arr[node] = 1;
        if (find(arr, leftChild[node])) {
            return find(arr, rightChild[node]);
        }
        return false;
    }

}
